<template>
  <div class="grouping">
    <div class="header">
      <ImportFile :on-success="success"></ImportFile>
      <el-button style="margin-left: 12px" @click="exportData" size="small" >导出</el-button>
      <el-button @click="groupBtn" size="small" type="danger">{{ timer ? '停止分组' : '开始分组' }}</el-button>
      <div class="pattern">
        <el-radio-group v-model="pattern">
          <el-radio :label="1" size="small" style="margin-right: 10px">模式一</el-radio>
          <el-radio :label="2" size="small">模式二</el-radio>
        </el-radio-group>
        <div class="pattern2" v-if="pattern == 2">
          <el-input-number v-model="pattern2Num" size="small" :min="1"/>
        </div>
        <div class="tip">
          <p>模式一: 每组人数 = 总人数 / 组长 (溢出人数随机添加到各个组中)</p>
          <p>模式二: 自己选择每组人数 (溢出人数不进行分配) </p>
        </div>
      </div>
      <div class="tip" style="color: #000">
        <p>当前组长/分组数量：{{groupLeaderList.length}}</p>
        <p>{{tableName}}</p>
      </div>
    </div>

    <el-table :data="list" stripe height="calc(100vh - 100px)" size="small">
      <el-table-column type="index" label="序号"  width="180"/>
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="groupLeader" label="组长" >
        <template #default="scope">
          <div>
            <el-switch  v-model="scope.row.groupLeader"></el-switch>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="group" label="当前分组"></el-table-column>

    </el-table>
    <div class="totalClass">共{{list.length}}条</div>
  </div>
</template>

<script setup>
import ImportFile from '@/components/import.vue'
import {computed, ref} from 'vue'
import { ElMessage } from 'element-plus'

const list = ref([])
const tableName = ref('')
// 组长分组数量
const groupLeaderList = computed(() => {
  return list.value.filter(el => el.groupLeader)
})

// 分组
let timer = ref(null)
const pattern = ref(1) // 分组模式
const pattern2Num = ref(1) // 模式2的小组人数

const groupBtn = () => {
  if(timer.value){
    return clearGroup()
  }
  timer.value = setInterval(() => {
    handlerGroup()
  }, 100)
}
const clearGroup = () => {
  clearInterval(timer.value)
  timer.value = null
}
const handlerGroup = () => {
  // 小组普通人员
  let totalList = list.value.filter(el => !el.groupLeader)
  const total = totalList.length
  if(!total){
    clearGroup()
    return ElMessage.info('请添加分组人员')
  }
  // grounp 组数, 根据组长判断
  const groupLeaderList = list.value.filter(el => el.groupLeader)
  const grounp = groupLeaderList.length
  if(!grounp){
    clearGroup()
    return ElMessage.info('请设置组长')
  }
  // 平均每组人数
  let qty = pattern.value === 2 ? pattern2Num.value - 1 : Math.floor(total / grounp)
  // 分组总集合
  const big_arr = []
  for(let i=0; i< grounp; i++){
    let small_arr = []
    for(let j=0; j<qty; j++){
      if(totalList.length <= 0) return
      let randomIndex = Math.floor(Math.random() * totalList.length)
      // totalList[randomIndex].group = `第${i+1}组`
      small_arr.push(totalList[randomIndex])
      totalList.splice(randomIndex, 1)
    }
    // 分配组长
    let groupRandomIndex = Math.floor(Math.random() * groupLeaderList.length)
    small_arr.unshift(groupLeaderList[groupRandomIndex])
    groupLeaderList.splice(groupRandomIndex, 1)
    big_arr.push(small_arr)
  }
  // 处理多余人数
  if(totalList.length > 0 && pattern.value === 1){
    for(let i=0; i<totalList.length; i++){
      big_arr[i].push(totalList[i])
    }
  }
  list.value = big_arr.reduce((a,b,i)=>{
    b.forEach(e => e.group = `第${i+1}组`)
    return a.concat(b)
  }, [])
  // 处理模式2
  if(totalList.length > 0 && pattern.value === 2){
    for(let i=0; i<totalList.length; i++){
      totalList[i].group = ``
      list.value.push(totalList[i])
    }
  }

}

// 导入成功
const success = ({header, result, fileName}) => {
  tableName.value = fileName
  const tableInfo = {
    '姓名': 'name',
  }
  let newArr = result.map(item => {
    let personnelInfo = {}
    Object.keys(item).forEach(key => {
      if (tableInfo[key] === 'timeOfEntry' || tableInfo[key] === 'correctionTime') {
        // 后端接口 限制了 不能是字符串 要求转化时间类型
        personnelInfo[tableInfo[key]] = new Date(formatDate(item[key], '/')) // 只有这样 才能存入数据库
      } else {
        personnelInfo[tableInfo[key]] = item[key] // 将原来中文对应的值 赋值给原来英文对应的值
      }
      personnelInfo.groupLeader = false
    })
    return personnelInfo
  })
  list.value = newArr || []
  ElMessage.success('导入成功!')
}

// 导出
const exportData = () => {
  const headers = {
    '姓名': "name",
    "组长": 'groupLeader',
    "当前分组": 'group'
  }
  import('@/vendor/Export2Excel').then(async excel => {
    const data = formatJson(headers, list.value)
    excel.export_json_to_excel({
      header: Object.keys(headers),
      data,
      fileName: tableName.value
    })
    ElMessage.success('导出成功!')
  })
}
// 将表头数据和数据进行对应
const formatJson = (headers, rows) => {
  return rows.map(item => {
    return Object.keys(headers).map(key => {
      if(headers[key] === 'groupLeader'){
        return item[headers[key]] ? '是' : '否'
      }else{
        return item[headers[key]]
      }
    })
  })
}

</script>

<style scoped lang='scss'>
@media screen and (min-width: 2500px){
  :deep(.el-table){
    .cell{
      line-height: 120px;
      font-size: 40px;
    }
  }
}

.grouping{
  .header{
    display: flex;
    align-items: center;
    height: 64px;
  }
  .pattern{
    display: flex;
    margin-left: 20px;
    align-items: center;
    .pattern2{
      margin-left: 10px;
    }
  }
  .tip{
    font-size: 12px;
    margin-left: 20px;
    color: #da9519;
  }
  .totalClass{
    font-size: 12px;
    margin-top: 10px;
  }
}
</style>
